package com.ebo.learn_demo.view

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.*
import android.text.Layout
import android.text.StaticLayout
import android.text.TextPaint
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.constraintlayout.widget.ConstraintHelper
import androidx.constraintlayout.widget.ConstraintLayout


/**
 * @author zmp
 * @date : 2021/12/20 16:28
 * des:ConstraintNewGuideBg
 */
class ConstraintNewGuideBg @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintHelper(context, attrs, defStyleAttr) {
    private val mTextPaint = TextPaint()
    private val mDrawList = mutableListOf<Pair<RectF, StaticLayout>>()
    override fun init(attrs: AttributeSet?) {
        super.init(attrs)
        mUseViewMeasure = true
    }

    private val mPath = Path()


    override fun updatePostLayout(container: ConstraintLayout) {
        super.updatePostLayout(container)
        mPath.reset()
        mDrawList.clear()
        referencedIds.forEach {
            val chideView = container.findViewById<View>(it)
            Log.e("ConstraintNewGuideBg", "updatePostLayout:$it $chideView")
            chideView ?: return@forEach
            val rectF = RectF(
                chideView.left.toFloat(),
                chideView.top.toFloat(),
                chideView.right.toFloat(),
                chideView.bottom.toFloat()
            )
            mPath.addRoundRect(
                rectF,
                5F, 5F,
                Path.Direction.CW
            )

            val message = "可以逐个计算每个字符的宽度，通过一定的算法将字符串分割成多个部分，然后分别调用"
            val myStaticLayout = StaticLayout(
                message,
                mTextPaint,
                width / 2,
                Layout.Alignment.ALIGN_NORMAL,
                1.0f,
                0.0f,
                false
            )
            mDrawList.add(rectF to myStaticLayout)
        }

    }


    @SuppressLint("DrawAllocation")
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.save()
        canvas.clipPath(mPath, Region.Op.DIFFERENCE)
        canvas.drawColor(Color.parseColor("#CC444444"))
        canvas.restore()
        mDrawList.forEach {
            val lineEnd = it.second.width
            canvas.save()
            canvas.translate(it.first.centerX() - lineEnd, it.first.bottom + mTextSize / 2)
            canvas.rotate(-45F, lineEnd - mTextSize / 2, 0F)
            it.second.draw(canvas)
            canvas.restore()
        }
    }

    private val mTextSize by lazy {
        40f
    }

    init {

        mTextPaint.color = Color.WHITE
        mTextPaint.style = Paint.Style.FILL
        mTextPaint.textSize = mTextSize
    }
}